package yunjiao.javatutorials.apache.kafka;

import com.github.javafaker.Faker;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import yunjiao.javatutorials.apache.kafka.model.Order;
import yunjiao.javatutorials.apache.kafka.model.OrderItem;
import yunjiao.javatutorials.apache.kafka.service.OrderService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 日志生成
 *
 * @author yangyunjiao
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProduceRunner implements CommandLineRunner {
    private final OrderService orderService;
    private final Faker faker = new Faker();

    private ScheduledThreadPoolExecutor scheduler;

    @PostConstruct
    public void postConstruct() {
        System.out.println("=== 订单任务启动 ===");
        scheduler = new ScheduledThreadPoolExecutor(1);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("=== 订单任务运行 ===");
        scheduler.scheduleWithFixedDelay(
                () -> {
                    log.info("=== 生成订单 ===");
                    OrderItem item = new OrderItem();
                    item.setQuantity(faker.number().numberBetween(0, 10));
                    item.setPrice(BigDecimal.valueOf(faker.number().randomDouble(2, 1, 10)));
                    item.setProductId(faker.idNumber().ssnValid());

                    Order order = new Order();
                    order.setOrderId(faker.idNumber().ssnValid());
                    order.setUserId(faker.idNumber().ssnValid());
                    order.setAmount(BigDecimal.valueOf(faker.number().randomDouble(2, 10, 100)));
                    order.setCreateTime(LocalDateTime.now());
                    order.setStatus("CREATE");
                    order.setItems(List.of(item));
                    orderService.createOrder(order);
                },
                2,  // 初始延迟
                3,  // 上次执行结束到下次执行开始的间隔
                TimeUnit.SECONDS
        );

    }

    @PreDestroy
    public void preDestroy() throws InterruptedException {
        System.out.println("=== 订单任务关闭 ===");
        // 优雅关闭
        scheduler.shutdown();
        if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) {
            scheduler.shutdownNow();
        }
    }

}
